package com.qf.user.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器，拦截所有登录相关操作(拦截含有login的请求)
//在方法执行前拦截
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求中相对路径
        String requestURI = request.getRequestURI();
        String[] strings = requestURI.split("/");
        String uri = strings[strings.length - 1];
        //判断如果含有js就放行
        if (uri.endsWith("js")){
            return true;
        }
        //如果请求中没有含有login
        if (!uri.contains("login")){
            //先查看是否是已登录状态，如果是则放行
            Object user = request.getSession().getAttribute("user");
            if (null!=user){
                return true;
            }
            //如果不是登录状态，则不放行并跳转至登录页面
            String loginPage = request.getContextPath() + "/login.html";
            response.sendRedirect(loginPage);
            return false;
        }
        return true;
    }
}
